package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

@Component
@Slf4j
public class OrdersTask {

    @Autowired
    OrderMapper orderMapper;


    /**
     *超时订单处理
     *每分钟检查一次
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        log.info("超时订单处理，{}", LocalDateTime.now());

        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);

        List<Orders> ordersList = orderMapper.getByOrderStatusAndTime(Orders.PENDING_PAYMENT,time);

        if(ordersList != null && ordersList.size() != 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.updateByOrderNumber(orders);
            }
        }

    }


    /**
     * 处理前一天的派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processOnDelivery(){
        log.info("对前一天派送中的订单进行处理");

        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);

        List<Orders> ordersList = orderMapper.getByOrderStatusAndTime(Orders.DELIVERY_IN_PROGRESS,time);

        if(ordersList != null && ordersList.size() != 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.updateByOrderNumber(orders);
            }
        }
    }
}
